/**
 * Customer Service Store - Ark Support Workbench
 * Manage chat rooms, messages, users, and statistics
 */

import { defineStore } from "pinia";
import { computed, ref } from "vue";
import {
  type ChatRoom,
  type ClientUser,
  createChatWithUser,
  getChatRooms,
  getClientUsers,
  type GetClientUsersParams,
  getRoomMessages,
  getRoomParticipants,
  getUserDetail,
  getUserSessions,
  hideRoom as hideRoomAPI,
  markRoomAsRead as markRoomAsReadAPI,
  type Message as ChatMessage,
  type Participant,
  restoreRoom as restoreRoomAPI,
  type RoomStatus,
  type UserDetail
} from "@/api/customer-service"; // 接口获取
import { customerServiceSocket } from "@/utils/websocket/customer-service";
import { ElMessage } from "element-plus";

export const useCustomerServiceStore = defineStore("customerService", () => {
  // State全局状态-在线客服
  const isConnected = ref(false);
  const rooms = ref<ChatRoom[]>([]);
  const newRooms = ref<ChatRoom[]>([]);
  const myRooms = ref<ChatRoom[]>([]);
  const resolvedRooms = ref<ChatRoom[]>([]);
  const currentRoomId = ref<number | null>(null);
  const messagesCache = ref<Record<number, ChatMessage[]>>({});
  const participantsCache = ref<Record<number, Participant[]>>({});
  const userDetailsCache = ref<Record<string, UserDetail>>({});
  const userSessionsCache = ref<Record<string, ChatRoom[]>>({});
  const typingUsers = ref<Record<number, number[]>>({});
  const loading = ref(false);

  // 用户列表相关
  const clientUsers = ref<ClientUser[]>([]);
  const clientUsersTotal = ref(0);
  const clientUsersLoading = ref(false);
  const clientUserSearchKeyword = ref("");

  //#region
  // Getters
  // 当前选中房间
  const currentRoom = computed(() => {
    if (!currentRoomId.value) return null;
    return rooms.value.find(room => room.id === currentRoomId.value);
  });
  // 当前房间消息
  const currentMessages = computed(() => {
    if (!currentRoomId.value) return [];
    return messagesCache.value[currentRoomId.value] || [];
  });
  // 当前房间参与者
  const currentParticipants = computed(() => {
    if (!currentRoomId.value) return [];
    return participantsCache.value[currentRoomId.value] || [];
  });
  // 未读消息总数
  const totalUnreadCount = computed(() => {
    return myRooms.value.reduce((sum, room) => sum + (room.unread_count || 0), 0);
  });
  // 新请求房间数
  const newRequestCount = computed(() => newRooms.value.length);
  // 我的房间总数
  const myRoomCount = computed(() => myRooms.value.length);
  //#endregion

  // WebSocket连接
  async function connectWebSocket() {
    try {
      await customerServiceSocket.connect();
      isConnected.value = true;
      setupWebSocketListeners();
      console.log("WebSocket connected");
    } catch (error) {
      console.error("WebSocket connection failed:", error);
      ElMessage.error("连接失败，请刷新重试");
      isConnected.value = false;
    }
  }
  // 断开WebSocket连接
  function disconnectWebSocket() {
    customerServiceSocket.disconnect();
    isConnected.value = false;
  }
  // 设置WebSocket事件监听
  function setupWebSocketListeners() {
    customerServiceSocket.on("new_message", handleNewMessage);
    customerServiceSocket.on("user_typing", handleUserTyping);
    customerServiceSocket.on("room_status_changed", handleRoomStatusChanged);
    customerServiceSocket.on("user_joined", handleUserJoined);
    customerServiceSocket.on("room_online_users_update", handleRoomOnlineUsersUpdate);
    customerServiceSocket.on("user_status_change", handleUserStatusChange);
    customerServiceSocket.on("error", handleSocketError);
  }

  // 加载房间（HTTP 拉取骨架）
  async function loadRooms(status?: RoomStatus) {
    loading.value = true;
    try {
      const { data: result } = await getChatRooms({ status, per_page: 20 });
      rooms.value = result.rooms;
      console.log("📦 [骨架] HTTP 加载房间列表:", result);

      // 分类房间
      categorizeRooms();

      // 🔥 加载完房间后，自动 join 所有房间以接收实时更新（WebSocket 填充血肉）
      if (isConnected.value && rooms.value.length > 0) {
        console.log("🔌 [血肉] 开始加入所有房间以接收实时更新...");
        rooms.value.forEach(room => {
          customerServiceSocket.joinRoom(room.id);
        });
        console.log(`✅ [血肉] 已加入 ${rooms.value.length} 个房间`);
      }

      return result;
    } catch (error) {
      console.error("Load rooms failed:", error);
      ElMessage.error("Failed to load rooms");
      throw error;
    } finally {
      loading.value = false;
    }
  }
  // 分类房间
  function categorizeRooms() {
    newRooms.value = rooms.value.filter(room => room.status === "new");
    myRooms.value = rooms.value.filter(room => room.type === "private");
    resolvedRooms.value = rooms.value.filter(room => room.status === "closed");
  }
  // 加载消息
  async function loadMessages(roomId: number, page = 1) {
    try {
      console.log("Loading messages for room:", roomId);
      const response = await getRoomMessages(roomId, { page, per_page: 50 });
      console.log("Messages response:", response);

      const messages = (response as any)?.data?.messages || response?.messages || [];
      console.log("Extracted messages:", messages);

      if (page === 1) {
        messagesCache.value[roomId] = [...messages];
      } else {
        messagesCache.value[roomId] = [...[...messages], ...(messagesCache.value[roomId] || [])];
      }

      console.log("Messages cached for room", roomId, ":", messagesCache.value[roomId]);
      console.log("第一条消息时间:", messagesCache.value[roomId][0]?.created_at);
      return response;
    } catch (error) {
      console.error("Load messages failed:", error);
      ElMessage.error("加载消息失败");
      // 初始化为空数组，避免后续错误
      if (!messagesCache.value[roomId]) {
        messagesCache.value[roomId] = [];
      }
      throw error;
    }
  }
  // 加载参与者
  async function loadParticipants(roomId: number) {
    try {
      const response = await getRoomParticipants(roomId);
      participantsCache.value[roomId] = (response as any)?.data?.participants || response?.participants || [];
      return response;
    } catch (error) {
      console.error("Load participants failed:", error);
      // 初始化为空数组
      if (!participantsCache.value[roomId]) {
        participantsCache.value[roomId] = [];
      }
      throw error;
    }
  }
  // 加载用户详情
  async function loadUserDetail(userId: number, userType: string) {
    const cacheKey = `${userId}_${userType}`;
    if (userDetailsCache.value[cacheKey]) {
      return userDetailsCache.value[cacheKey];
    }
    try {
      const result = await getUserDetail(userId, userType as any);
      userDetailsCache.value[cacheKey] = result.user;
      return result.user;
    } catch (error) {
      console.error("Load user detail failed:", error);
      throw error;
    }
  }
  // 加载用户会话
  async function loadUserSessions(userId: number, userType: string) {
    const cacheKey = `${userId}_${userType}`;
    try {
      const result = await getUserSessions(userId, userType as any);
      userSessionsCache.value[cacheKey] = result.sessions;
      return result.sessions;
    } catch (error) {
      console.error("Load user sessions failed:", error);
      throw error;
    }
  }
  // 房间操作
  // 选择房间, 加载消息和参与者
  async function selectRoom(roomId: number) {
    console.log("Selecting room:", roomId);
    currentRoomId.value = roomId;
    if (!messagesCache.value[roomId]) {
      await loadMessages(roomId);
    }
    if (!participantsCache.value[roomId]) {
      await loadParticipants(roomId);
    }
    /**

    try {
      if (!messagesCache.value[roomId]) {
        await loadMessages(roomId);
      }
    } catch (err) {
      console.error("Failed to load messages, initializing empty array", err);
      messagesCache.value[roomId] = [];
    }

    try {
      if (!participantsCache.value[roomId]) {
        await loadParticipants(roomId);
      }
    } catch (err) {
      console.error("Failed to load participants, initializing empty array", err);
      participantsCache.value[roomId] = [];
    }

    **/
    if (isConnected.value) {
      customerServiceSocket.joinRoom(roomId);
    }
    markRoomAsRead(roomId);
  }
  // 发送消息
  function sendMessage(roomId: number, content: string, type: any = "text") {
    if (!isConnected.value) {
      ElMessage.error("Not connected to server");
      return;
    }
    customerServiceSocket.sendMessage(roomId, content, type);
  }
  // 发送输入状态
  function sendTypingStatus(roomId: number, isTyping: boolean) {
    if (!isConnected.value) return;
    customerServiceSocket.sendTyping(roomId, isTyping);
  }

  // WebSocket 事件处理器
  // 收到新消息后的处理
  function handleNewMessage(msg: ChatMessage) {
    console.log("通过WebSocket收到的信息:", msg);
    const roomId = msg.room_id;
    // 如果没有房间，先置空聊天记录
    if (!messagesCache.value[roomId]) {
      messagesCache.value[roomId] = [];
    }
    // 将新消息添加到缓存
    messagesCache.value[roomId].push(msg);

    const room = rooms.value.find(r => r.id === roomId);
    if (room) {
      room.last_message = msg;
      room.updated_at = msg.created_at;
      if (currentRoomId.value !== roomId && !msg.is_own) {
        room.unread_count = (room.unread_count || 0) + 1;
      }

      // 🔥 更新参与者信息（头像、昵称、在线状态等）
      // WebSocket 返回的 sender 包含更多字段，使用类型断言
      if (msg.sender && room.participants) {
        const sender = msg.sender as any; // WebSocket 返回的完整用户信息
        const senderInRoom = room.participants.find(p => p.id === sender.id && p.type === sender.type);

        if (senderInRoom) {
          // 更新现有参与者信息
          senderInRoom.name = sender.name;
          if (sender.avatar) {
            senderInRoom.avatar = sender.avatar;
          }
          // 处理在线状态（可能是 online_status 或 is_online）
          if (sender.online_status !== undefined) {
            senderInRoom.online_status = sender.online_status;
          } else if (sender.is_online !== undefined) {
            senderInRoom.online_status = sender.is_online;
          }
          // 更新手机号
          if (sender.phone) {
            senderInRoom.phone = sender.phone;
          }
          // 更新邮箱
          if (sender.email) {
            senderInRoom.email = sender.email;
          }
        } else {
          // 如果发送者不在参与者列表中，添加进去
          room.participants.push({
            id: sender.id,
            type: sender.type,
            name: sender.name,
            avatar: sender.avatar,
            online_status: sender.online_status ?? sender.is_online ?? false,
            phone: sender.phone,
            email: sender.email
          });
        }
      }

      // 同步更新 participantsCache,用于私聊窗口显示
      if (participantsCache.value[roomId] && msg.sender) {
        const sender = msg.sender as any;
        const cachedParticipant = participantsCache.value[roomId].find(
          p => p.id === sender.id && p.type === sender.type
        );

        if (cachedParticipant) {
          cachedParticipant.name = sender.name;
          if (sender.avatar) {
            cachedParticipant.avatar = sender.avatar;
          }
          if (sender.online_status !== undefined) {
            cachedParticipant.online_status = sender.online_status;
          } else if (sender.is_online !== undefined) {
            cachedParticipant.online_status = sender.is_online;
          }
          if (sender.phone) {
            cachedParticipant.phone = sender.phone;
          }
          if (sender.email) {
            cachedParticipant.email = sender.email;
          }
        }
      }
    }

    rooms.value.sort((a, b) => new Date(b.updated_at).getTime() - new Date(a.updated_at).getTime());
    categorizeRooms();
  }

  function handleUserTyping(data: any) {
    const { room_id, user, is_typing } = data;
    if (!typingUsers.value[room_id]) {
      typingUsers.value[room_id] = [];
    }
    if (is_typing) {
      if (!typingUsers.value[room_id].includes(user.id)) {
        typingUsers.value[room_id].push(user.id);
      }
    } else {
      typingUsers.value[room_id] = typingUsers.value[room_id].filter(id => id !== user.id);
    }
  }

  function handleRoomStatusChanged(data: any) {
    const { room_id, status } = data;
    const room = rooms.value.find(r => r.id === room_id);
    if (room) {
      room.status = status;
      categorizeRooms();
    }
  }

  function handleUserJoined(data: any) {
    const { room_id, user } = data;
    if (participantsCache.value[room_id]) {
      const exists = participantsCache.value[room_id].some(p => p.id === user.id && p.type === user.type);
      if (!exists) {
        participantsCache.value[room_id].push(user);
      }
    }
  }

  // 🔥 处理房间在线用户更新（WebSocket 推送完整的在线用户列表）
  // 注意: 此事件已被禁用,因为会与 user_status_change 事件冲突
  // user_status_change 提供更精确的单个用户状态更新,避免批量更新覆盖问题
  function handleRoomOnlineUsersUpdate(data: any) {
    const { room_id, online_users } = data;
    console.log(`🩸 [血肉] 收到房间 ${room_id} 的在线用户更新 (已禁用):`, online_users);
    console.log("⚠️ 此事件已被禁用,使用 user_status_change 代替");
  }

  // 🔥 处理用户状态变化（用户上线/下线）
  function handleUserStatusChange(data: any) {
    const { user, is_online } = data;
    console.log(`👤 [状态变化] 用户 ${user.name} (${user.id}) ${is_online ? "上线" : "下线"}:`, data);

    // 更新所有包含该用户的房间
    rooms.value.forEach(room => {
      if (room.participants) {
        const participantIndex = room.participants.findIndex(p => p.id === user.id && p.type === user.type);
        console.log(`🔍 房间 ${room.id} 查找用户 ${user.id}/${user.type}, 找到索引: ${participantIndex}`);
        if (participantIndex !== -1) {
          const oldData = { ...room.participants[participantIndex] };
          // ✅ 创建新对象替换,触发响应式更新
          room.participants[participantIndex] = {
            ...room.participants[participantIndex],
            is_online: is_online,
            online_status: is_online ? "在线" : "离线",
            name: user.name,
            avatar: user.avatar,
            phone: user.phone
          };
          console.log(`✅ 房间 ${room.id} 中用户 ${user.name} 状态已更新:`);
          console.log(`   旧值: is_online=${oldData.is_online}, online_status=${oldData.online_status}`);
          console.log(
            `   新值: is_online=${room.participants[participantIndex].is_online}, online_status=${room.participants[participantIndex].online_status}`
          );
        }
      }
    });
    console.log("🔄 同步更新 participantsCache 中的用户状态...");
    console.log("rooms.value结果值:", rooms.value);
    // 同步更新所有相关的 participantsCache - 创建新数组触发响应式
    Object.keys(participantsCache.value).forEach(roomIdStr => {
      const roomId = parseInt(roomIdStr);
      const participants = participantsCache.value[roomId];
      if (participants) {
        const participantIndex = participants.findIndex(p => p.id === user.id && p.type === user.type);
        if (participantIndex !== -1) {
          // ✅ 创建新数组替换,触发响应式更新
          participantsCache.value[roomId] = participants.map((p, index) => {
            if (index === participantIndex) {
              return {
                ...p,
                is_online: is_online,
                online_status: is_online ? "在线" : "离线",
                name: user.name,
                avatar: user.avatar,
                phone: user.phone
              };
            }
            return p;
          });
        }
      }
    });
  }
  // 🔥 处理 WebSocket 错误
  function handleSocketError(data: any) {
    console.error("WebSocket error:", data);
    ElMessage.error(data.message || "Communication error");
  }

  // Helper methods
  // 标记房间为已读
  async function markRoomAsRead(roomId: number) {
    // 先更新本地未读数
    const room = rooms.value.find(r => r.id === roomId);
    if (room && room.unread_count && room.unread_count > 0) {
      room.unread_count = 0;

      // 调用后端 API 标记为已读
      try {
        await markRoomAsReadAPI(roomId);
        console.log(`Room ${roomId} marked as read`);
      } catch (error) {
        console.error("Failed to mark room as read:", error);
        // 静默失败，不影响用户体验
      }
    }
  }

  // 隐藏会话（软删除）
  async function hideRoom(roomId: number) {
    try {
      const response = await hideRoomAPI(roomId);
      console.log("Hide room response:", response);

      // 从本地列表中移除该房间
      rooms.value = rooms.value.filter(r => r.id !== roomId);
      categorizeRooms();

      // 如果当前选中的是这个房间，清除选择
      if (currentRoomId.value === roomId) {
        clearSelection();
      }

      // 清理缓存
      delete messagesCache.value[roomId];
      delete participantsCache.value[roomId];

      const message = response.data?.room_deleted ? "会话已删除（双方均已删除）" : "会话已删除";
      ElMessage.success(message);

      return response;
    } catch (error) {
      console.error("Failed to hide room:", error);
      ElMessage.error("删除会话失败");
      throw error;
    }
  }

  // 恢复会话
  async function restoreRoom(roomId: number) {
    try {
      const response = await restoreRoomAPI(roomId);
      console.log("Restore room response:", response);

      // 重新加载房间列表
      await loadRooms();

      ElMessage.success("会话已恢复");
      return response;
    } catch (error) {
      console.error("Failed to restore room:", error);
      ElMessage.error("恢复会话失败");
      throw error;
    }
  }

  function clearSelection() {
    if (currentRoomId.value && isConnected.value) {
      customerServiceSocket.leaveRoom(currentRoomId.value);
    }
    currentRoomId.value = null;
  }

  function reset() {
    disconnectWebSocket();
    rooms.value = [];
    newRooms.value = [];
    myRooms.value = [];
    resolvedRooms.value = [];
    currentRoomId.value = null;
    messagesCache.value = {};
    participantsCache.value = {};
    userDetailsCache.value = {};
    userSessionsCache.value = {};
    typingUsers.value = {};
    clientUsers.value = [];
    clientUsersTotal.value = 0;
  }

  // ==================== 用户列表管理 ====================

  /**
   * 加载客户端用户列表
   */
  async function loadClientUsers(params?: GetClientUsersParams) {
    try {
      clientUsersLoading.value = true;
      const { data } = await getClientUsers(params);
      console.log("Loaded client users:", data);
      if (data) {
        clientUsers.value = data.list;
        clientUsersTotal.value = data.total;
      }
    } catch (error) {
      console.error("Failed to load client users:", error);
      ElMessage.error("加载用户列表失败");
    } finally {
      clientUsersLoading.value = false;
    }
  }

  /**
   * 搜索用户
   */
  async function searchClientUsers(keyword: string) {
    clientUserSearchKeyword.value = keyword;
    await loadClientUsers({
      keyword,
      per_page: 50
    });
  }

  /**
   * 创建与用户的聊天
   */
  async function startChatWithUser(userId: number) {
    try {
      loading.value = true;
      const response: any = await createChatWithUser(userId);
      console.log("Create chat response:", response);

      // 处理后端返回的数据格式 (后端实际返回 { data: { room_id, type, name, ... } })
      const roomData = response?.data || response?.room;
      const roomId = roomData?.room_id || roomData?.id;

      if (roomId) {
        // 重新加载房间列表以获取完整的房间信息
        await loadRooms();
        // 选中这个房间
        await selectRoom(roomId);
        ElMessage.success("已创建会话");
      }
    } catch (error) {
      console.error("Failed to create chat with user:", error);
      ElMessage.error("创建会话失败");
    } finally {
      loading.value = false;
    }
  }

  return {
    // State
    isConnected,
    rooms,
    newRooms,
    myRooms,
    resolvedRooms,
    currentRoomId,
    messagesCache,
    participantsCache,
    userDetailsCache,
    userSessionsCache,
    typingUsers,
    loading,
    // Client Users
    clientUsers,
    clientUsersTotal,
    clientUsersLoading,
    clientUserSearchKeyword,
    // Getters
    currentRoom,
    currentMessages,
    currentParticipants,
    totalUnreadCount,
    newRequestCount,
    myRoomCount,
    // WebSocket
    connectWebSocket,
    disconnectWebSocket,
    // Data loading
    loadRooms,
    loadMessages,
    loadParticipants,
    loadUserDetail,
    loadUserSessions,
    // Room operations
    selectRoom,
    sendMessage,
    sendTypingStatus,
    markRoomAsRead,
    hideRoom,
    restoreRoom,
    // Client Users operations
    loadClientUsers,
    searchClientUsers,
    startChatWithUser,
    // Helper methods
    clearSelection,
    reset
  };
});
